package com.atguigu.gmall.product.controller;


import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.product.service.TestService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.stream.Collectors;

@Api(tags = "测试接口")
@RestController
@RequestMapping("admin/product/test")
public class TestController {

    @Autowired
    private TestService testService;

    @GetMapping("testLock")
    public Result testLock() throws InterruptedException {
        testService.testLock();
        return Result.ok();
    }


    /**
     * 读数据接口
     *
     * @return
     */
    @GetMapping("/read")
    public Result read() {
        String msg = testService.read();
        return Result.ok(msg);
    }

    /**
     * 写数据接口
     *
     * @return
     */
    @GetMapping("/write")
    public Result write() {
        testService.write();
        return Result.ok("写入数据成功");
    }


    @GetMapping("/testAsync")
    public String testAsync(String data) {
        String result = testService.testAsync(data);
        return result;
    }


    /**
     * 保存用户信息
     * 如果校验参数失败,将错误信息封装到对象
     *
     * @param bindingResult 必须放在校验对象后面;只有校验参数失败 才有值
     * @param user
     * @return
     */
    @PostMapping("/saveUser")
    public Result saveUser(@Valid @RequestBody TestUserDTO dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            //遍历有错误字段获取提示信息响应给前端
            String errorMsg = bindingResult.getFieldErrors().stream().map(FieldError::getDefaultMessage)
                    .collect(Collectors.joining(","));
            throw new RuntimeException(errorMsg);
        }
        System.out.println("模拟保存用户");
        return Result.ok();
    }
}
